#! /usr/bin/env python
#coding=utf-8
import os
import io
import StringIO
import unittest
import HostsLibaray 


class TestHostsLibarayBackUp(unittest.TestCase):
    def setUp(self):
        self.Host = HostsLibaray.Hosts()
    def tearDown(self):
        self.Host.clear()    
        
    def testAddHostsMapping(self):
        self.Host.Add({'192.168.10.5':'www.sina.com'})
        self.assertEqual(self.Host.GetMappingsByHost('192.168.10.5'),('www.sina.com',))
        
    def testDeleteHostsMapping(self):
        self.Host.Add({'192.168.10.5':'www.sina.com'})
        self.Host.Delete({'192.168.10.5':'www.sina.com'})
        self.assertEqual(self.Host.GetMappingsByHost('192.168.10.5'),None)
    
    def testDeleteWhenNotInMappings(self):
        self.assertRaises(HostsLibaray.DeleteException, self.Host.Delete, {'192.168.10.5':'www.sina.com'})
           
    def testAddHostMappingWhenHasKeyInMappings(self):
        self.Host.Add({'192.168.10.5':'www.sina.com'})
        self.Host.Add({'192.168.10.5':'www.baidu.com'})
        list = self.Host.GetMappingsByHost('192.168.10.5')
        self.assertEqual(list,('www.sina.com', 'www.baidu.com',))
        
    def testPutaway(self):
        self.Host.Add({'192.168.10.5':'www.sina.com'})
        self.Host.Putaway({'192.168.10.5':'www.sina.com'})
        self.assertEqual(self.Host.GetMappingsByHost('192.168.10.5'), None)
        self.assertEqual(self.Host.GetPutawayMappings('#192.168.10.5'), ('www.sina.com',))
        
    def testDeleteFromPutwayMappings(self):
        self.Host.Add({'192.168.10.5':'www.sina.com'})
        self.Host.Putaway({'192.168.10.5':'www.sina.com'})
        self.Host.DeletePutawayMapping({'#192.168.10.5':'www.sina.com'})
        self.assertEqual(self.Host.GetPutawayMappings('192.168.10.5'), None)       

    def testSaveLoad(self):
        self.Host.Add({'192.168.10.5':'www.sina.com', '192.168.10.15':'www.sinnnn.com'})
        self.Host.Putaway({'192.168.10.5':'www.sina.com'})
        
        Stream = StringIO.StringIO()
        self.Host.save(Stream)
        Stream.seek(0)
        for line in Stream:
            print line
        self.Host.clear()
        self.assertEqual(self.Host.GetAllMappings(), {})
        self.assertEqual(self.Host.GetAllPutawayMappings(), {})
        Stream.seek(0)
        self.Host.load(Stream)
        self.assertEqual(self.Host.GetAllMappings(), {'192.168.10.15':['www.sinnnn.com',]})
        self.assertEqual(self.Host.GetAllPutawayMappings(), {'#192.168.10.5':['www.sina.com',]})


 
if __name__ == '__main__':
    unittest.main()
 